#include <time.h>
#include <sys/timeb.h>
#include <unistd.h>
#include "xdebug.h"

int DebugInfo(int level, FILE *fd, int line, char *file, char *format, ...)
{
    struct  timeb  tmb;
    time_t         tmNow;
    struct  tm     *tmstru;
    //char           fmt[1024];
    char           buffer[2048 + 1];
    va_list        arg;
    int            done;
    int            maxlen = 2048;

    if (NULL == fd)
        return -1;

    time(&tmNow);
    tmstru = localtime(&tmNow);
    ftime(&tmb);

    if (fd == stdout || fd == stderr)
    {
        if (level == 1){
            fprintf(fd, "\33[31m\33[47m");
        }else if (level == 2){
            fprintf(fd, "\33[35m");
        }else if (level == 3){
            fprintf(fd, "\33[33m");
        }else if (level == 4){
            fprintf(fd, "\33[37m");
        }
    }
    //strcpy(fmt, "%02d%02d %02d:%02d:%02d-%03d %d,%d %s:%d ");
    //strcat(fmt, format);
    fprintf(fd, "%02d%02d %02d:%02d:%02d-%03d %d %s:%d ", tmstru->tm_mon+1, tmstru->tm_mday, tmstru->tm_hour,
            tmstru->tm_min, tmstru->tm_sec, tmb.millitm,
            getpid(), file, line);

    va_start (arg, format);
    done = vsnprintf (buffer, maxlen, format, arg);
    va_end (arg);

    fprintf(fd, "%s", buffer);
    fflush(fd);
    if (fd == stdout || fd == stderr)
    {
        fprintf(fd, "\33[0m");
    }

    return 0;
}

